package com.bitdf.txing.common.utils;

import com.alibaba.fastjson.JSON;
import com.bitdf.txing.common.constant.CommonConstant;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.to.UserTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author Lizhiwei
 * @date 2023/2/7 1:26:45
 * 注释：
 */
@Slf4j
public class UserUtils {
    public static void returnJson(HttpServletResponse response,Integer code){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            R r = R.error(code, TxCodeEnume.getMsgByCode(code));
            writer.print(r);
        } catch (IOException e){
            log.error("未登录");
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }

    /**
     * 登录+权限 校验
     * @param request
     * @param response
     * @param level 用户必须登录 且 用户等级与level指定数值相等才给予放行
     * @param redisTemplate
     * @param threadLocal
     * @return
     */
    public static boolean isPerm(HttpServletRequest request, HttpServletResponse response, Integer level, StringRedisTemplate redisTemplate, ThreadLocal<UserTo> threadLocal) {
        //获取请求头Authorization
        String authorization = request.getHeader("token");
        if (authorization==null){
            //未登录即转发到指定路径
            UserUtils.returnJson(response, TxCodeEnume.USER_NOT_LOGIN_EXCEPTION.getCode());
            return false;
        }
        //获取redis中指定key的操作对象
        BoundHashOperations<String, Object, Object> cartOps = RedisUtils.getBoundOps(CommonConstant.USER_SESSION_KEY_PREFIX+authorization,redisTemplate);
        String s = (String) cartOps.get("loginUser");
        if (s==null){
            //未登录即转发到指定路径
            UserUtils.returnJson(response, TxCodeEnume.USER_NOT_LOGIN_EXCEPTION.getCode());
            return false;
        }
        //重置该用户在redis的信息的有效时间
        cartOps.expire(30, TimeUnit.MINUTES);

        //把redis中拿出的json数据转换为UserEntity类型
        UserTo user = JSON.parseObject(s, UserTo.class);

        //权限校验
        if(level!=null && !user.getLevelId().equals(level)){
            UserUtils.returnJson(response,TxCodeEnume.USER_NOT_PERM_EXCEPTION.getCode());
            return false;
        }

        //把user存入当前线程中，以方便在业务代码中获取
        threadLocal.set(user);

        return true;
    }
}
